<?php
/**
 * Created by PhpStorm.
 * User: kcswag
 * Date: 12/27/17
 * Time: 10:04 PM
 */

namespace AppBundle\Libs\MessageQueue;

use swoole_client;

class Client
{
    protected $host;
    protected $port;
    protected $client;
    protected $type;
    protected $timeout;

    public function __construct($host,$port, $timeout = -1, $type = SWOOLE_SOCK_TCP)
    {
        $this->host = $host;
        $this->port = $port;
        $this->type = SWOOLE_SOCK_TCP;
        $this->timeout = $timeout;

        $this->client = new swoole_client($this->type);
        if(!$this->client->connect($this->host,$this->port,$this->timeout)){
            die("connect failed.");
        }
    }

    public function send($data){
        if (!$this->client->send("{$data}\n"))
        {
            die("send failed.");
        }
    }

    public function receive(){
        return $this->client->recv();
    }

    public function close(){
        return $this->client->close();
    }

    public function killServer(){
        $data = serialize(['switch'=>'shutdown']);
        $this->client->send($data);
        $res = $this->client->recv();
        return $res==='Server stopped' ? true : false;
    }

    public function reloadServer(){
        $data = serialize(['switch'=>'reload']);
        $this->client->send($data);
        $res = $this->client->recv();
        return $res==='Server reloaded' ? true : false;
    }

    public function __destruct()
    {
        $this->client->close();
    }

}